package www.truongnha.com;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import Config.setting;
import TruongNhaLib.DatabaseHandler;
import TruongNhaLib.JSONParser;
import TruongNhaLib.Model;
import TruongNhaLib.StudentAdapter;
import TruongNhaLib.UserFunctions;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;

public class Students extends ListActivity {
	Boolean reload = false;
	Boolean saved = true;
	Boolean submitPermission = false;// Only mainteacher have permission to
										// submit
	// Constant id for actions
	private static final int HOME_ID = 0;
	private static final int DATE_ID = 1;
	private static final int SUBMIT_ID = 2;
	static final int DATE_DIALOG_ID = 0;
	private Button btn_m;
	private Button btn_c;
	private Button btn_k;
	private Button btn_save;
	private int mYear;
	private int mMonth;
	private int mDay;
	private static String host = setting.getHost();
	private static String getStudentListURL = host + "api/attendance/";
	private String name;
	private String classId;
	private String currentDate;
	private List<Model> list = new ArrayList<Model>();
	ArrayAdapter<Model> adapter;
	Toast toast;
	private int[] result = new int[4];

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.submit_attendance);
		// Create a Toast object for all toast notification
		toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);

		// Create db object:
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		// Get data for main Class
		ArrayList<HashMap<String, String>> mainClass = db.getMainClassDetail();

		// getting intent data
		Intent in = getIntent();
		this.name = in.getStringExtra("class");
		this.classId = in.getStringExtra("classId");
		Log.d("student", "02" + "classId" + classId + " name " + name);

		// Create action bar for this activity:
		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new myAction(HOME_ID,
				R.drawable.ic_back));
		actionBar.setTitle("" + name);
		actionBar.addDateAction(new myAction(DATE_ID,
				R.drawable.ic_title_export_default));
		// Only main teacher can submit attendance
		if (mainClass.get(0).get("classId").equals(classId)) {
			submitPermission = true;
			Button btn_save = (Button) findViewById(R.id.btn_save);
			btn_save.setEnabled(false);// disable this button, because nothing
										// change
			// actionBar.addAction(new myAction( SUBMIT_ID,
			// R.drawable.ic_title_export_default) );
		} else {
			// hide save button on toolbar
			LinearLayout toolbar = (LinearLayout) findViewById(R.id.toolbar);
			toolbar.setWeightSum(3);
			Button btn_save = (Button) findViewById(R.id.btn_save);
			btn_save.setVisibility(View.GONE);
		}
		Log.d("student", "03");
		// Get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH) + 1;// Because MONTH begin at zero to
											// eleven :|
		mDay = c.get(Calendar.DAY_OF_MONTH);
		currentDate = mDay + "-" + mMonth + "-" + mYear;
		// Display the current date (this method is implement later)
		updateDisplay();
		// Listen
		btn_m = (Button) findViewById(R.id.btn_m);
		btn_m.setOnClickListener(btn_m_c_k_save_listener);
		btn_c = (Button) findViewById(R.id.btn_c);
		btn_c.setOnClickListener(btn_m_c_k_save_listener);
		btn_k = (Button) findViewById(R.id.btn_k);
		btn_k.setOnClickListener(btn_m_c_k_save_listener);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_save.setOnClickListener(btn_m_c_k_save_listener);

		// Create an adapter
		adapter = new StudentAdapter(Students.this, list, result, btn_m, btn_c,
				btn_k, btn_save, submitPermission);
		Log.d("student", "04");
		// Get data from servers
		// list = (ArrayList<Model>)getLastNonConfigurationInstance();
		Log.d("student", "05");
		// if(list == null){
		// Log.d("getStudentListURL111", getStudentListURL +classId+'/'+mDay
		// +'/' +mMonth +'/'+mYear+'/');
		new getStudentListTask().execute(getStudentListURL + classId + '/'
				+ mDay + '/' + mMonth + '/' + mYear + '/');
		// }
		Log.d("student", "06");
		// Set adapter
		if (findViewById(R.id.grid) != null) {
			Log.d("gridview", "Khac null");
			GridView grid = (GridView) findViewById(R.id.grid);
			grid.setAdapter(adapter);
		} else {
			setListAdapter(adapter);
		}

		// Listen to Launch new screen on Selecting Single ListItem
		if (findViewById(R.id.grid) != null) {
			Log.d("gridview", "Khac null");
			GridView grid = (GridView) findViewById(R.id.grid);
			// grid.setOnItemClickListener(onItemClickListenner);
			grid.setOnItemLongClickListener(onItemLongClickListenner);
		} else {
			// selecting single ListView item
			ListView lv = getListView();
			// lv.setOnItemClickListener(onItemClickListenner);
			lv.setOnItemLongClickListener(onItemLongClickListenner);
		}
	}// end onCreate

	@Override
	public Object onRetainNonConfigurationInstance() {
		// TODO Auto-generated method stub
		return list;
	}

	// Create listener
	// Listener for m_c_k_save button click
	OnClickListener btn_m_c_k_save_listener = new OnClickListener() {
		public void onClick(View v) {
			toast = Toast.makeText(getApplicationContext(), "",
					Toast.LENGTH_SHORT);
			switch (v.getId()) {
			case R.id.btn_m:
				toast.setText("Đi học muộn " + result[2]);
				toast.show();
				break;
			case R.id.btn_c:
				toast.setText("Nghỉ học có phép " + result[1]);
				toast.show();
				break;
			case R.id.btn_k:
				toast.setText("Nghỉ học không phép " + result[0]);
				toast.show();
				break;
			case R.id.btn_save:
				submitAttendance();
				break;
			default:
				break;
			}
		}
	};
	OnItemLongClickListener onItemLongClickListenner = new OnItemLongClickListener() {
		@SuppressWarnings("deprecation")
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			// getting values from selected ListItem
			Model aStd = list.get(position);
			AlertDialog alertDialog = new AlertDialog.Builder(Students.this)
					.create();
			alertDialog.setTitle(aStd.getIndex() + ". " + aStd.getName());
			alertDialog.setCancelable(true);
			int status = aStd.getStatus();
			switch (status) {
			case 0:// Nghi hoc ko phep
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Nghỉ học không phép" + "\n"
						+ "Điện thoại:" + aStd.getPhone() + "\n" + "Email: "
						+ aStd.getEmail());
				break;
			}
			case 1:// Nghi hoc co phep
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Nghỉ học có phép" + "\n"
						+ "Điện thoại:" + aStd.getPhone() + "\n" + "Email: "
						+ aStd.getEmail());
				break;
			}
			case 2:// Di hoc muon
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Đi học muộn" + "\n" + "Điện thoại:"
						+ aStd.getPhone() + "\n" + "Email: " + aStd.getEmail());
				break;
			}
			case 3:// Di hoc
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Đi học" + "\n" + "Điện thoại:"
						+ aStd.getPhone() + "\n" + "Email: " + aStd.getEmail());
				break;
			}
			default:
				break; // Should never occur
			}
			alertDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimationTopDown;
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			// Add phone call button if phone is not null
			if (!aStd.getPhone().equals("")) {
				alertDialog.setButton2("Gọi điện",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});
			}
			alertDialog.show();
			return true;
		}
	};

	OnItemClickListener onItemClickListenner = new OnItemClickListener() {
		@SuppressWarnings("deprecation")
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// getting values from selected ListItem
			Model aStd = list.get(position);
			AlertDialog alertDialog = new AlertDialog.Builder(Students.this)
					.create();
			alertDialog.setTitle(aStd.getIndex() + ". " + aStd.getName());
			alertDialog.setCancelable(true);
			int status = aStd.getStatus();
			switch (status) {
			case 0:// Nghi hoc ko phep
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Nghỉ học không phép" + "\n"
						+ "Điện thoại:" + aStd.getPhone() + "\n" + "Email: "
						+ aStd.getEmail());
				break;
			}
			case 1:// Nghi hoc co phep
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Nghỉ học có phép" + "\n"
						+ "Điện thoại:" + aStd.getPhone() + "\n" + "Email: "
						+ aStd.getEmail());
				break;
			}
			case 2:// Di hoc muon
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Đi học muộn" + "\n" + "Điện thoại:"
						+ aStd.getPhone() + "\n" + "Email: " + aStd.getEmail());
				break;
			}
			case 3:// Di hoc
			{
				alertDialog.setMessage("Ngày sinh: " + aStd.getBirth() + "\n"
						+ "Giới tính : " + aStd.getSex() + "\n"
						+ "Trạng thái: " + "Đi học" + "\n" + "Điện thoại:"
						+ aStd.getPhone() + "\n" + "Email: " + aStd.getEmail());
				break;
			}
			default:
				break; // Should never occur
			}
			alertDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimationTopDown;
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			// Add phone call button if phone is not null
			if (!aStd.getPhone().equals("")) {
				alertDialog.setButton2("Gọi điện",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});
			}
			alertDialog.show();
		}
	};

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {

		// Always call the superclass so it can save the view hierarchy state
		super.onSaveInstanceState(savedInstanceState);
	}

	// Updates the date in the TextView
	private void updateDisplay() {
		Button button = (Button) findViewById(R.id.actionbar_text_item);
		button.setText(currentDate);
	}// end updateDisplay

	// The callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			if (!currentDate.equals(mDay + "-" + mMonth + "-" + mYear)) {// If
																			// date
																			// change
				currentDate = mDay + "-" + mMonth + "-" + mYear;
				updateDisplay();
				new getStudentListTask().execute(getStudentListURL + classId
						+ '/' + mDay + '/' + mMonth + '/' + mYear + '/');
			}
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear,
					mMonth - 1, mDay);
		}
		return null;
	}

	// Estimate result
	public void computeResult() {
		result[0] = 0;// K
		result[1] = 0;// C
		result[2] = 0;// M
		result[3] = list.size();// Size
		int status;
		for (int i = 0; i < result[3]; i++) {
			status = list.get(i).getStatus();
			if (status == 0)
				result[0]++;
			if (status == 1)
				result[1]++;
			if (status == 2)
				result[2]++;
		}
	}

	// Submit attendance
	public void submitAttendance() {
		// Send attendList to server.
		UserFunctions userFunction = new UserFunctions();
		JSONStringer string = new JSONStringer();// {"id":603031,"mark":[{"m":5.5,"n":1}]}
		try {
			string = string.object().key("id").value(603031).key("mark")
					.array().object().key("m").value(10).key("n").value(1)
					.endObject().endArray().endObject();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("submit", string.toString());
		int statusCode = userFunction.submitMark(host + "api/markForASubject",
				string.toString());

		// int statusCode = userFunction.postStudentList(list, currentDate,
		// classId);
		switch (statusCode) {
		case 200: {
			Toast.makeText(getApplicationContext(),
					"Đã điểm danh lớp " + name + "\n Ngày " + currentDate,
					Toast.LENGTH_SHORT).show();
			saved = true;
			btn_save.setBackgroundResource(R.drawable.selector_save_button_1);
			btn_save.setText("Đã lưu");
			btn_save.setEnabled(false);// disable this button, changed submited
			adapter.notifyDataSetChanged();
			break;
		}
		case -1: {
			Toast.makeText(getApplicationContext(),
					"Lớp đi học đầy đủ " + name + "\n Ngày " + currentDate,
					Toast.LENGTH_SHORT).show();
			saved = true;
			btn_save.setBackgroundResource(R.drawable.selector_save_button_1);
			btn_save.setText("Đã lưu");
			btn_save.setEnabled(false);
			adapter.notifyDataSetChanged();
			break;
		}
		default: {
			Toast.makeText(
					getApplicationContext(),
					"Try again!!!!!!!!!!!!!!" + name + "\n Ngày " + currentDate,
					Toast.LENGTH_SHORT).show();
			break;
		}
		}
	}

	@Override
	public void onBackPressed() {
		if (btn_save.getText().toString().equals("Lưu lại"))
			saved = false;// Not save, remind save
		if (submitPermission && !saved) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(true)
					.setIcon(R.drawable.alert_icon)
					.setTitle("Bạn chưa lưu điểm danh!")
					.setPositiveButton("Lưu lại",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									submitAttendance();
								}
							})
					.setNegativeButton("Bỏ qua",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
									Students.this.finish();
									Students.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
								}
							});
			AlertDialog alert = builder.create();
			alert.getWindow().getAttributes().windowAnimations = R.style.DialogAnimationTopDown;
			alert.show();
		} else {
			Students.this.finish();
			Students.this.overridePendingTransition(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
		}
	}// End onBackPressed

	// AsyncTask for getStudentList:
	class getStudentListTask extends AsyncTask<String, Void, List<Model>> {
		ProgressDialog dialog;
		String message;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("Task", "onPreExecute");
			message = "";
			dialog = new ProgressDialog(Students.this);
			dialog.setMessage("Loading...");
			dialog.show();
			Log.d("Task", "onPreExecute");
		}

		@Override
		protected List<Model> doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.d("Task", "doInBackground");
			list.clear();
			JSONArray students = new JSONParser()
					.getJSONArray(params[0]);
			int SIZE = students.length();
			if (SIZE == 1) {// May be receive error message or one student.
				try {
					message = students.getString(0);
					Log.d("mess", message);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(message.equals("")){//no error
				try {
					int index;
					for (int i = 0; i < SIZE; i++) {
						index = i + 1;
						JSONObject student = students.getJSONObject(i);
						Model aStd = new Model(student.getString("id"), index,
								student.getString("lastName") + " "
										+ student.getString("firstName"),
								student.getString("DOB"), student.getString("sex"),
								3);
						aStd.setEmail(student.getString("email"));
						String status = student.getString("status");
						if (status.equals("")) {
							aStd.setStatus(3);// Di hoc
						} else {
							if (status.equals("M")) {// Di muon
								aStd.setStatus(2);
							} else {
								if (status.equals("P")) {// Co phep
									aStd.setStatus(1);
								} else {
									if (status.equals("K")) {// Ko phep
										aStd.setStatus(0);
									}
								}
							}
						}// end if to set status
						aStd.setPhone(student.getString("phone"));
						list.add(aStd);
					}// End for
				} catch (JSONException e) {
					e.printStackTrace();
				}// End try
			}
			Log.d("Task", "Done doInBackground..");
			Log.d("list", "size = " + list.size());
			return list;
		}

		@Override
		protected void onPostExecute(List<Model> result) {
			if (!message.equals("")) {//error.
				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_SHORT).show();
			}else{//no error.
				runOnUiThread(new Runnable() {
					public void run() {
						Log.d("data", "change to " + adapter.getCount());
						computeResult();
						btn_m.setText(Students.this.result[2] + " - M");
						btn_c.setText(Students.this.result[1] + " - C");
						btn_k.setText(Students.this.result[0] + " - K");
						adapter.notifyDataSetChanged();
					}
				});
			}
			dialog.dismiss();
		}
	}// End class getStudentListTask

	// Class myAction
	private class myAction extends AbstractAction {
		private int actionId;

		public myAction(int actionId, int resId) {
			super(resId);
			this.actionId = actionId;
		}

		public void performAction(View view) {
			switch (actionId) {
			case HOME_ID:// Action 0 touched! Back to home
				Students.this.onBackPressed();
				break;
			case SUBMIT_ID:// Action 1 touched! Submit to server
				submitAttendance();
				break;
			case DATE_ID:// Action 1 touched! date
				showDialog(DATE_DIALOG_ID);
				break;
			default:
				break;
			}
		}// end perform
	}// end myAction class

}// End Students.java
